package com.ta.gulimall.common.exception;

import com.ta.gulimall.common.enums.BizCodeEnums;
import com.ta.gulimall.common.utils.system.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.ta.gulimall.common.enums.BizCodeEnums.VAILD_EXCEPTION;

@RestControllerAdvice(basePackages = {"com.ta.gulimall"})
@Slf4j
public class gulimallControllerAdvice {

    @ExceptionHandler(value = BindException.class)
    public R handValidException(BindException e){
        return Optional.ofNullable(e.getFieldError())
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .map(m -> R.error(BizCodeEnums.FAILURE_EXCEPTION.getCode(), m))
                .orElse(R.error());
    }

    @ExceptionHandler(value = RuntimeException.class)
    public R unknownException(RuntimeException e){
        log.error("系统异常:" + e.getMessage(), e);
        return R.error(BizCodeEnums.FAILURE_EXCEPTION.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public R unknownException(Exception e){
        log.error("系统异常:" + e.getMessage(), e);
        return R.error(BizCodeEnums.FAILURE_EXCEPTION.getCode(), BizCodeEnums.FAILURE_EXCEPTION.getMessage());
    }

}
